package com.smartfast4j.chat.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * 聊天客户端启动入口
 */
public class SimpleChatClient {

    private String host;
    private int port;

    public SimpleChatClient(String host,int port){
        this.host = host;
        this.port = port;
    }

    public void run() {
        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            bootstrap
                    .group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new SimpleChatClientInitializer());
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            Channel channel = channelFuture.channel();//获取和服务端连接的channel
            //接收控制台的输入
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while (true){
                String msg = in.readLine();
                if(msg.equals("exit")){
                    break;
                }
                //向服务端发送消息
                channel.writeAndFlush(msg + "\r\n");
            }
            channel.closeFuture();//关闭Channel，断开和服务端的连接
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            eventLoopGroup.shutdownGracefully();//释放资源
        }
    }

    public static void main(String[] args){
        new SimpleChatClient("127.0.0.1",9999).run();
    }
}
